import { useHistory, useLocation } from "react-router-dom";
import { NavBar } from "antd-mobile";
import styles from "./index.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useRef, useState } from "react";
import { clearArticle, getSearchResults } from "@/store/actions/search";
import { RootState } from "@/types/store";
import Icon from "@/components/Icon";
import { InfiniteScroll } from "antd-mobile";

const Result = () => {
  const history = useHistory();
  // 下面的一顿操作拿到了search里面的参数
  const location = useLocation();
  console.log(location);
  const params = new URLSearchParams(location.search);
  console.log(params);
  const keyword = params.get("key") as string;
  console.log(keyword);
  const dispatch = useDispatch();
  const { results, resLength } = useSelector((state: RootState) => state.search);
  console.log(resLength, "======================================================resLength");

  //! 下面用了无限滚动，所以这里就不需要加载了
  // useEffect(() => {
  //   dispatch(getSearchResults(keyword, 1));
  // }, [dispatch, keyword]);

  // 是否有更多数据
  const [hasMore, setHasMore] = useState(true);
  // 加载状态
  const [loading, setLoading] = useState(false);
  // 每次上传的页数
  const page = useRef(1);
  // 无限加载
  const loadMore = async () => {
    if (loading) return;
    setLoading(true);
    // 加载更多文章列表，后面存储形式已修改
    await dispatch(getSearchResults(keyword, page.current));
    page.current = page.current + 1;
    console.log(page.current);

    setLoading(false);
    if (resLength === 0) {
      setHasMore(false);
    }
  };

  // 跳转到文章详情页面
  const gotoAritcleDetail = (articleId: string) => {
    history.push(`/article/${articleId}`);
  };
  // 组件销毁的时候把article数据清除掉
  useEffect(() => {
    return () => {
      dispatch(clearArticle());
    };
  }, [dispatch]);
  return (
    <div className={styles.root}>
      <NavBar className="topNavBar" onBack={() => history.go(-1)}>
        搜索结果
      </NavBar>
      <div className="article-list">
        {results.map((item) => (
          <div className="result-item" key={item.art_id} onClick={() => gotoAritcleDetail(item.art_id)}>
            <Icon className="icon-search" type="icon-sousuo2" />
            <div className="result-value text-overflow"> {item.title}</div>
          </div>
        ))}
      </div>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  );
};

export default Result;
